const bcrypt = require('bcrypt');
const { ethers } = require('ethers');
const db = require('../config/db');

const User = {
  // 创建用户，密码加密并生成钱包地址和私钥
  create: async (userData) => {
    // 使用 bcrypt 加密密码
    const hashedPassword = await bcrypt.hash(userData.password, 10);
    
    // 使用 ethers.js 生成钱包地址和私钥
    const wallet = ethers.Wallet.createRandom();
    const mnemonic = wallet.mnemonic.phrase;
    const walletAddress = wallet.address;
    const privateKey = wallet.privateKey;

    const query = `INSERT INTO users (username, password, email, phone, points_balance, role, wallet_address) 
                   VALUES (?, ?, ?, ?, ?, ?, ?)`;
    const values = [
      userData.username,
      hashedPassword,  // 存储加密后的密码
      userData.email,
      userData.phone,
      userData.points_balance || 0.0,
      userData.role || '普通用户',
      walletAddress // 存储生成的钱包地址
    ];

    // 插入数据库
    const results = await new Promise((resolve, reject) => {
      db.query(query, values, (error, results) => {
        if (error) return reject(error);
        resolve(results);
      });
    });

    // 返回结果和私钥
    return {
      userId: results.insertId,
      walletAddress,
      mnemonic,
      privateKey, // 返回生成的私钥以便下载
      
    };
  },

  // 根据邮箱查找用户
  findByEmail: async (email) => {
    const query = `SELECT * FROM users WHERE email = ?`;
    return new Promise((resolve, reject) => {
      db.query(query, [email], (error, results) => {
        if (error) return reject(error);
        resolve(results[0]);  // 返回第一个匹配的用户
      });
    });
  }
};



module.exports = User;



